package server;

import game.Map;
import game.Player;
import game.ScoreList;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import javax.swing.JOptionPane;

public class Client extends Thread{
	
	private Map map;
	private Player player;
	private Socket socket;
	private ScoreList score;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;

	public static void main(String argv[]) {
		new Client();
	}

	public Client() {
		try {
			socket = new Socket("localhost", 3000);
			oos = new ObjectOutputStream(socket.getOutputStream());
			ois = new ObjectInputStream(socket.getInputStream());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.start();
	}
	

	public void move(String direcetion, Player player)
	{
		Data tempData = new Data(direcetion, player);
		
	}

	public void run() {
		try {
		String in = JOptionPane.showInputDialog("Indtast dit spillernavn");
		map = map.getInstance(oos);
		player = new Player(in);
		map.addPlayer(player);
		oos.writeObject(player);
		oos.flush();
		while (true) {
				Object o = ois.readObject();
				if(o instanceof Map){
					Map tempMap = (Map) o;
					for(int i = 0; i < tempMap.getPlayers().size(); i++)
					{
						if(!tempMap.getPlayers().get(i).getName().equals(player.getName()))
							map.addPlayer(tempMap.getPlayers().get(i));
					}
				}
				else if (o instanceof Data) {
					Data tempData = (Data) o;
					if(!tempData.getPlayer().equals(player))
					{
						map.playerMoved(tempData.getMove(), tempData.getPlayer());
					}
				}
				else if (o instanceof Player) {
					Player tempPlayer = (Player) o;
//						if(!tempPlayer.getName().equals(player.getName()))
//							tempPlayer.addPlayer(tempPlayer);
//					}
				}
		}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
	}
}
